﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using Mbs.Elements;
using Mbs.Modularity.AddIns;
using Mbs.ComponentModel.Container;

namespace Mbs.Windows.Elements.Builders
{
    public class ToolStripBuilder<TToolStrip> : ElementBuilder where TToolStrip : ToolStrip,new()
    {
        [Inject]
        public IElementService ElementService { protected get; set; }


        public override object Create(object caller, IAddInItem element)
        {
            Debug.Assert(element != null, "element == null");

            return CreateToolStrip(caller, element);

        }

        public override void InitInstance(object caller, IAddInItem element, List<object> subItems, object instance)
        {
            if (subItems == null || instance == null) return;

            var toolStrip = instance as TToolStrip;
            if (toolStrip != null)
            {
                foreach (var item in subItems)
                    if (item is ToolStripItem)
                        ElementService.Sites[element.Path].Add(item, null);
            }
        }

        private TToolStrip CreateToolStrip(object caller, IAddInItem element)
        {
            TToolStrip toolStrip = new TToolStrip();
            toolStrip.Name = element.Path;
            toolStrip.Tag = element;

            var disposeCollector = caller as IDisposeCollector;
            if (disposeCollector != null)
                disposeCollector.Disposes.Add(new DisposeAction(toolStrip, () => toolStrip.Dispose()));

            ElementService.Sites.RegisterSite(element.Path, toolStrip);

            return toolStrip;
        }

    }


    [Component(Id = "ToolStrip", Service = typeof(IElementBuilder))]
    public class ToolStripBuilder : ToolStripBuilder<ToolStrip>
    {
    }
}